package mspbots.qbd.online.oauth;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * com.mspbots.doctor.response.RedirectAuthController
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/19
 */
@Log4j2
@Controller
@RequestMapping("client")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @GetMapping("redirect")
    public Mono<String> redirect(@RequestParam Map<String, Object> params, Model model) {
        log.debug("Oauth2.0 redirect call params {}", params);
        return this.authorize(params)
                .map(authorizationCode -> model.addAttribute("token", authorizationCode.getAccessToken()))
                .map(val -> "redirect");
    }

    @ResponseBody
    @GetMapping("authorize")
    public Mono<AuthorizationCode> authorize(@RequestParam Map<String, Object> params) {
        log.debug("Oauth 2.0 redirect call back params {}", params);
        Assert.notNull(params.get("state"), () -> "Login params [state] not null. ");
        Assert.notNull(params.get("code"), () -> "Login params [code] not null. ");
        return this.authService.authToken(params);
    }

    @ResponseBody
    @GetMapping("token")
    public Mono<TokenState> getToken(@RequestParam Long tenantId) {
        log.debug("Refresh Token params tenantId is {}", tenantId);
        return this.authService.getToken(tenantId);
    }

}
